package com.fourforfo.fourmall.order.config;

import com.xxl.sso.core.conf.Conf;
import com.xxl.sso.core.util.CookieUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @program: xxl-sso-core
 * @description: feign远程接口配置，为Feign接口添加拦截器
 * @author: fourforfo
 * @email: fourforfo@gmail.com
 * @create: 2022-09-01 14:17
 **/
@Configuration
public class FourmallFeignConfig {

    @Bean("requestInterceptor")
    public RequestInterceptor requestInterceptor(){
        return new RequestInterceptor(){
            @Override
            public void apply(RequestTemplate template){
                //从RequestContextHolder中获取请求信息
                ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
                if(servletRequestAttributes==null) return;
                HttpServletRequest request = servletRequestAttributes.getRequest();
                HttpServletResponse response = servletRequestAttributes.getResponse();
                //同步请求头数据，cookie
                String cookie = request.getHeader("Cookie");
                //设置请求参数
                String sessionId = request.getParameter(Conf.SSO_SESSIONID);
                if(!StringUtils.isEmpty(sessionId)){
                    template.query(Conf.SSO_SESSIONID,sessionId);
                }

                //将旧请求的cookie保存到新请求中
                template.header("Cookie",cookie);
            }
        };
    }

}
